package timing.ukulele.user.receiver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import timing.ukulele.user.model.MailBean;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeUtility;

import java.io.UnsupportedEncodingException;

import static timing.ukulele.user.config.TopicConfig.EMAIL_ROUTING;

@Component
@Slf4j
public class MailReceiver {
    private final JavaMailSender mailSender;
    private final MailProperties mailProperties;

    public MailReceiver(JavaMailSender mailSender, MailProperties mailProperties) {
        this.mailSender = mailSender;
        this.mailProperties = mailProperties;
    }

    @RabbitHandler
    @RabbitListener(queues = EMAIL_ROUTING )
    public void emailReceiver(MailBean mailBean) {
        log.info("接收到了要发送的邮件：" + mailBean.getToAccount());
        this.sendMail(mailBean);
    }

    /**
     * 发送邮件测试方法
     */
    public void sendMail(MailBean mailBean) {
        try {
            SimpleMailMessage mimeMessage = new SimpleMailMessage();
            mimeMessage.setFrom(mailProperties.getUsername());
            mimeMessage.setTo(mailBean.getToAccount());
            mimeMessage.setSubject(mailBean.getSubject());
            mimeMessage.setText(mailBean.getContent());
            mailSender.send(mimeMessage);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

    /**
     * 发送邮件-附件邮件
     *
     * @param mailBean
     */
    public boolean sendMailAttachment(MailBean mailBean) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(mailBean.getToAccount());
            helper.setSubject(mailBean.getSubject());
            helper.setText(mailBean.getContent(), true);
            // 增加附件名称和附件
            helper.addAttachment(MimeUtility.encodeWord(mailBean.getAttachmentFileName(), "utf-8", "B"), mailBean.getAttachmentFile());
            mailSender.send(mimeMessage);
            return true;
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }
}
